package api

import (
	"github.com/valyala/fasthttp"
	"strings"
)

var (
	corsAllowMethods = "HEAD,GET,POST"
	corsAllowOrigin  = []string{"gaodun.com",
		"gaodunwangxiao.com",
		"gaodun.cn",
		"hishixi.com",
		"xiucai.com",
	}
	corsAllowCredentials = "true"
)

func SetApiCorsHeader(ctx *fasthttp.RequestCtx) bool {
	origin := string(ctx.Request.Header.PeekBytes([]byte("HTTP_ORIGIN")))
	var allow bool = false
	for _, v := range corsAllowOrigin {
		if strings.Contains(origin, v) {
			ctx.Response.Header.Set("Access-Control-Allow-Credentials", corsAllowCredentials)
			ctx.Response.Header.Set("Access-Control-Allow-Methods", corsAllowMethods)
			ctx.Response.Header.Set("Access-Control-Allow-Origin", origin)
			allow = true
			break
		}
	}
	if !allow {
		return false
	}

	return true
}

func SetApiCustomHeader(ctx *fasthttp.RequestCtx) {
	ctx.Response.Header.Set("Cache-Control", "no-cache")
	ctx.Response.Header.SetServerBytes([]byte("ucenter-api v1.0.0"))
	ctx.SetContentType("application/json; charset=utf8")
}
func SetApiAllowCorsHeader(ctx *fasthttp.RequestCtx) {
	origin := string(ctx.Request.Header.PeekBytes([]byte("HTTP_ORIGIN")))
	ctx.Response.Header.Set("Access-Control-Allow-Credentials", corsAllowCredentials)
	ctx.Response.Header.Set("Access-Control-Allow-Methods", corsAllowMethods)
	ctx.Response.Header.Set("Access-Control-Allow-Origin", origin)
	SetApiCustomHeader(ctx)
}

func SetApiHeader(ctx *fasthttp.RequestCtx) {
	SetApiCorsHeader(ctx)
	SetApiCustomHeader(ctx)
	ctx.SetConnectionClose()
}
